import os, re, json, random
from .models import Ms, sjq, sdxx, qd, st
from django.http import JsonResponse
from django.forms import ModelForm
from django.shortcuts import render, HttpResponse, redirect
from .jlfx import ImageUnderstanding
from django.views.decorators.csrf import csrf_exempt
from .ztfx import SparkModel


id = 0


class Myform(ModelForm):
    class Meta:
        model = Ms
        fields = ['name', 'phone', 'password']



def login(request):
    if request.method == 'POST':
        name = request.POST.get('user')
        password = request.POST.get('password')
        phone = request.POST.get('phone')
        if Ms.objects.filter(phone=phone).exists():
            error_message = "该手机号已被注册"
            return render(request, 'login.html', {'error_message': error_message})
        #print(name, password, phone)
        Ms.objects.create(name=name, phone=phone, password=password)
        return render(request, 'login.html')


    return render(request, 'login.html', )


def main(request):
    if request.method == 'POST':
        phone = request.POST.get('ph')
        password = request.POST.get('ps')
        #print(phone, password)
        if not Ms.objects.filter(phone=phone).exists():
            error_message = "该手机号不存在"
            return render(request, 'login.html', {'error_message': error_message})
        if not Ms.objects.filter(password=password).exists():
            error_message = "密码错误"
            return render(request, 'login.html', {'error_message': error_message})
        if not Ms.objects.filter(phone=phone, password=password).exists():
            error_message = "密码错误或手机号错误"
            return render(request, 'login.html', {'error_message': error_message})
        name = Ms.objects.filter(phone=phone).values('name')[0]['name']
        #print(name)
        global id
        id = Ms.objects.filter(phone=phone).values('id')[0]['id']


        #request.session["info"] = {'password': Ms.objects.password, 'phone': Ms.objects.phone}
        return render(request, 'main.html', {'name': name})

    return render(request, 'login.html')


def mnms(request):
    global id
    name = Ms.objects.filter(id=id).values('name')[0]['name']

    return render(request, 'mnms.html', {'name': name})


def changeinfo(request):
    global id
    name = Ms.objects.filter(id=id).values('name')[0]['name']
    #print(id, name)
    return render(request, 'changeinfo.html', {'name': name})


def info(request):
    global id
    if request.method == 'POST':
        #print(request.POST)
        #print(request.POST['newname'], request.POST['newpassword'])
        n = request.POST.get('newname')
        p = request.POST.get('newpassword')
        Ms.objects.filter(id=id).update(name=n, password=p)
        name = Ms.objects.filter(id=id).values('name')[0]['name']
        phone = Ms.objects.filter(id=id).values('phone')[0]['phone']
        password = Ms.objects.filter(id=id).values('password')[0]['password']
        return render(request, 'info.html', {'name': name, 'password': password, 'phone': phone})

    name = Ms.objects.filter(id=id).values('name')[0]['name']
    phone = Ms.objects.filter(id=id).values('phone')[0]['phone']
    password = Ms.objects.filter(id=id).values('password')[0]['password']
    return render(request, 'info.html', {'name': name, 'password': password, 'phone': phone})



def pic(request):
    global id
    if request.method == 'POST':
        file_path = "简历.png"
        fill_object = request.FILES.get('avatar')
        #print(fill_object.name)
        f = open("简历.png", 'wb')
        for chunk in fill_object.chunks():
            f.write(chunk)
        f.close()
        # 分析简历
        analyzer = ImageUnderstanding()
        result = analyzer.analyze_resume()
        # 删除文件
        if os.path.exists(file_path):
            os.remove(file_path)

        grade = 0
        for i in range(len(result)):
            if result[i] == '分':
                # 查找“分”前面的连续数字
                match = re.search(r'\d+(?=(?:\D|$))', result[:i])
                if match:
                    grade = int(match.group())
                    break
        Ms.objects.filter(id=id).update(jl_grade=grade, jl=result)
        return HttpResponse("上传成功")


@csrf_exempt
def get_q(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            direction = data.get("direction")

            # 根据方向选择对应的模型
            if direction == "数据库":
                question_model = sjq
            elif direction == "深度学习":
                question_model = sdxx
            elif direction == "前端":
                question_model = qd
            elif direction == "数通":
                question_model = st
            else:
                return JsonResponse({"error": "无效的方向"}, status=400)

            # 获取对应方向的所有题目
            all_questions = list(question_model.objects.values())

            # 确保题库数据足够20条
            if len(all_questions) < 20:
                return JsonResponse({"error": f"{direction}题库数据不足20条"}, status=400)

            # 随机选择20条不重复的数据
            random_questions = random.sample(all_questions, 20)

            # 按ID排序（可选，保持一致性）
            random_questions.sort(key=lambda x: x['id'])
            #print(random_questions)
            return JsonResponse({"questions": random_questions}, status=200)

        except Exception as e:
            return JsonResponse({"error": str(e)}, status=500)
    else:
        return JsonResponse({"error": "只允许 POST 请求"}, status=405)


@csrf_exempt
def save(request):
    global id
    if request.method == 'POST':
        try:
            data = json.loads(request.body)  # 手动解析 JSON 数据
            print("Received data:", data)

            # 示例：提取数据
            exam_score = data.get('exam_score')
            interview_score = data.get('interview_score')
            posture_score = data.get('posture_score')
            expression_score = data.get('expression_score')
            eye_contact_score = data.get('eye_contact_score')
            fx = data.get('fx')
            print(exam_score, interview_score, posture_score, expression_score, eye_contact_score, fx)
            Ms.objects.filter(id=id).update(exam_score=exam_score, interview_score=interview_score, posture_score=posture_score, expression_score=expression_score, eye_contact_score=eye_contact_score, fx =fx)


            # 保存到数据库或其他逻辑
            return JsonResponse({"status": "success", "received": data})
        except json.JSONDecodeError:
            return JsonResponse({"status": "error", "message": "Invalid JSON"}, status=400)
    else:
        return JsonResponse({"status": "error", "message": "Only POST requests allowed"}, status=405)

def msjl(request):
    global id
    if not Ms.objects.filter(id=id).values('exam_score')[0]['exam_score']:
        return HttpResponse("您还未进行面试，请返回先进行面试")
    name = Ms.objects.filter(id=id).values('name')[0]['name']
    fx = Ms.objects.filter(id=id).values('fx')[0]['fx']
    jl = Ms.objects.filter(id=id).values('jl')[0]['jl']
    jl_grade = Ms.objects.filter(id=id).values('jl_grade')[0]['jl_grade']
    bs = Ms.objects.filter(id=id).values('exam_score')[0]['exam_score']
    ms = Ms.objects.filter(id=id).values('interview_score')[0]['interview_score']
    posture_score = Ms.objects.filter(id=id).values('posture_score')[0]['posture_score']
    expression_score = Ms.objects.filter(id=id).values('expression_score')[0]['expression_score']
    eye_contact_score = Ms.objects.filter(id=id).values('eye_contact_score')[0]['eye_contact_score']
    average_grade = (jl_grade + bs + ms) / 3
    spark = SparkModel()
    result = spark.main(fx, bs, jl_grade, ms)
    print(result)

    return render(request, 'msjl.html', {'name': name, 'fx': fx, 'jl': jl, 'jl_grade': jl_grade, 'result': result, 'average_grade' : average_grade, 'posture_score': posture_score, 'expression_score': expression_score, 'eye_contact_score': eye_contact_score})
